import { exec } from 'child_process'

export function runAppleScript(script: string, isJxa = true) {
  return new Promise<string>((resolve, reject) => {
    const escapedScript = script.replace(/'/g, "\\'")
    const command = `osascript ${isJxa ? '-l JavaScript' : ''} -e '${escapedScript}'`
    exec(command, (error, stdout, stderr) => {
      if (error) {
        reject(error)
      }
      if (stderr) {
        reject(stderr)
      }

      // 去除结尾的换行符
      resolve(stdout.replace(/\n$/, ''))
    })
  })
}

const jxaGetWinState = `
const winState = {};
const frontmostApp = Application("System Events").applicationProcesses.where({
  frontmost: true,
});

winState.activeAppPath = frontmostApp[0].file().posixPath();
//从路径中获取应用名
winState.appName = winState.activeAppPath.split("/").pop() || "";

//如果当前是finder
if (winState.appName === "Finder.app") {
  const finder = Application("Finder");
  winState.finderSel = finder.selection().map((item) => {
    const url = item.url();
    const decodedUrl = decodeURI(url);
    const path = decodedUrl.slice(7);
    return path;
  });

  try {
    const url = finder.insertionLocation().url();
    const decodedUrl = decodeURI(url);
    winState.finderDir = decodedUrl.slice(7);
  } catch (e) {}
}

JSON.stringify(winState);
`
//平均200ms执行耗时
export const getWinState = (): Promise<WinState> => {
  return runAppleScript(jxaGetWinState).then((res) => {
    return JSON.parse(res) as WinState
  })
}
